<template>
  <el-row>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片组件 -->
    <el-card class="box-card">
      <!-- 警告提示组件 -->
      <el-alert title="注意: 只允许为第三级分类设置相关的参数" type="warning" show-icon :closable="false"></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            :options="cateList"
            v-model="selectKeys"
            @change="handleChange"
            :props="cateOption"
            expand-trigger="hover"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 组件 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数 -->
          <el-button
            size="small"
            type="primary"
            :disabled="isBtnDisabled"
            @click="isaddDialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数数据展示表格 -->
          <el-table :data="manyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagHandleClose(index, scope.row)"
                >{{item}}</el-tag>
                <!-- v-if="scope.row.inputVisible" 控制是显示文本输入框还是按钮 -->
                <!-- v-model="scope.row.inputValue" 是在文本框中输入的值 -->
                <!-- @keyup.enter.native 是指输入之后,可以按回车输入内容 -->
                <!-- @blur 鼠标失去焦点时触发 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性 -->
          <el-button
            size="small"
            type="primary"
            :disabled="isBtnDisabled"
            @click="isaddDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态参数数据展示表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数  属性 对话框 -->
    <el-dialog
      :title="'添加' + addText"
      :visible.sync="isaddDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加文本框 -->
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="100px">
        <el-form-item :label="addText" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isaddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数  属性 对话框 -->
    <el-dialog
      :title="'修改' + addText"
      :visible.sync="iseditDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 修改文本框 -->
      <el-form :model="editRuleForm" :rules="editRules" ref="editRuleFormRef" label-width="100px">
        <el-form-item :label="addText" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="iseditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  name: 'params',
  data () {
    return {
      // 分类列表数据
      cateList: [],
      // 选中的分类 id 数组
      selectKeys: [],
      cateOption: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 控制添加对话框是否显示
      isaddDialogVisible: false,
      // 添加参数数据
      addRuleForm: {
        attr_name: ''
      },
      // 添加参数规则
      addRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改参数数据
      editRuleForm: {
        attr_name: ''
      },
      // 修改数据验证规则
      editRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改对话框时候显示
      iseditDialogVisible: false,
      // 修改的数据的 Id 值
      attrId: null
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.cateList = res.data
    },
    // 当分类发生改变时触发
    async handleChange () {
      this.getParamsData()
    },
    // tab 栏切换时
    handleClick () {
      this.getParamsData()
    },
    // 对获取数据进行封装
    async getParamsData () {
      // 当 selectKeys 的长度不为 3 的时候,即选中的类不为三级的时候,将 selectKeys 清空
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

      res.data.forEach(item => {
        // item.attr_vals = item.attr_vals.split(' ')
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })

      // 这里需要判断,判断是动态参数还是静态设置
      // 然后进行赋值
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 当添加对话框关闭时,重置规则
    addDialogClose () {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 点击添加确认按钮,完成添加操作
    addParamsInfo () {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return this.$msg.error('添加失败')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addRuleForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$msg.error(res.meta.msg)
        this.$msg.success(res.meta.msg)
        this.getParamsData()
        this.isaddDialogVisible = false
      })
    },
    // 点击编辑按钮,出发编辑事件
    async showEditDialog (attrId) {
      this.attrId = attrId
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { patams: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.editRuleForm.attr_name = res.data.attr_name
      this.iseditDialogVisible = true
    },
    // 编辑对话框关闭时,重置表单验证
    editDialogClose () {
      this.$refs.editRuleFormRef.resetFields()
    },
    // 点击确认修改按钮
    async editParams () {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.attrId}`, {
        attr_name: this.editRuleForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
      this.getParamsData()
      this.iseditDialogVisible = false
    },
    // 删除参数
    async deleteParams (attrId) {
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$msg.info('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.selectKeys}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$msg.eror(res.meta.msg)
      this.$msg.success(res.meta.msg)
      this.getParamsData()
    },
    // 按下回车键或文本框失去焦点时触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 将数据追加到渲染的数据数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.updateParams(row)
    },
    // 封装添加或删除参数后,渲染页面,封装函数的方法
    async updateParams (row) {
      // 将数据同步到服务器
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
    },
    // 点击按钮切换到文本框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除选项
    tagHandleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.updateParams(row)
    }
  },
  computed: {
    // 控制按钮是否被禁用
    isBtnDisabled () {
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取选中的项的 Id
    cateId () {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return ''
    },
    // 判断点击的哪个按钮
    addText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 20px;
  span {
    margin-right: 10px;
  }
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 120px;
}
</style>
